<template>
  <div>
    <a-button v-if="!chatVisible" class="chat-float-button" type="primary" shape="circle" @click="toggleChat">
      <template #icon>
        <MessageOutlined />
      </template>
    </a-button>
    <div v-else class="chat-container">
      <div class="chat-header">
        <div class="header-content">
          <h3>智能助手</h3>
          <a-button type="text" @click="toggleChat" :icon="h(CloseOutlined)" class="close-button" />
        </div>
      </div>
      <div class="chat-messages" ref="messagesContainer">
        <div v-for="(message, index) in messages" :key="index" :class="['message', message.type]">
          <div class="message-content">{{ message.content }}</div>
          <div class="message-time">{{ message.time }}</div>
        </div>
      </div>
      <div class="chat-input">
        <a-input v-model:value="inputMessage" placeholder="请输入消息..." @keyup.enter="sendMessage" />
        <a-button type="primary" @click="sendMessage">发送</a-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, inject, reactive, h } from 'vue'
import { MessageOutlined, CloseOutlined } from '@ant-design/icons-vue'

// 注入事件总线
const emitter = inject('emitter')

// 聊天面板显示状态
const chatVisible = ref(false)

// 切换聊天面板显示/隐藏
const toggleChat = () => {
  chatVisible.value = !chatVisible.value
}

// 聊天消息列表
const messages = ref([
  { content: '您好，我是智能助手，有什么可以帮助您的？', type: 'received', time: formatTime() }
])

// 输入框内容
const inputMessage = ref('')

// 消息容器引用，用于自动滚动
const messagesContainer = ref(null)

// sse: 服务端推送 Server-Sent Events
const eventSource = ref(null);
const count = ref(0);

// 发送消息
function sendMessage() {
  if (!inputMessage.value.trim()) return
  if (eventSource.value) {
    eventSource.value.close();
  }

  // 添加用户消息
  const userMessage = {
    content: inputMessage.value,
    type: 'sent',
    time: formatTime()
  }
  messages.value.push(userMessage)
  scrollToBottom()
  // 等待回复
  messages.value.push({
    content: '正在思考中...',
    type: 'received',
    time: formatTime()
  })
  count.value = messages.value.length - 1;

  // 清空输入框
  const userInput = inputMessage.value
  inputMessage.value = ''

  eventSource.value = new EventSource(`http://localhost:8080/ai/generateStreamAsString?message=${userInput}`);
  eventSource.value.onmessage = (event) => {
    const data = event.data;
    console.log(data);
    if (data === '[complete]') {
      eventSource.value.close();
      //根据返回的消息类型，发送全局事件，相应的页面接收事件进行处理
      // 发送全局事件，传递用户输入的消息
      emitter.emit('chat-send-message', userInput);
      emitter.emit('chat-received-message', messages.value.content);
      return;
    }
    messages.value[count.value].content += data;
    messages.value[count.value].time = formatTime()
    scrollToBottom()
  };
  // 
  eventSource.value.onopen = (event) => {
    messages.value[count.value].content = '';
  };
}

// 格式化时间
function formatTime() {
  const now = new Date()
  const hours = now.getHours().toString().padStart(2, '0')
  const minutes = now.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 滚动到底部
function scrollToBottom() {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 组件挂载后滚动到底部
onMounted(() => {
  scrollToBottom()
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 500px;
  width: 350px;
  border: 1px solid #e8e8e8;
  background-color: #fff;
  overflow: hidden;
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 1000;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.chat-float-button {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 48px;
  height: 48px;
  font-size: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
}

.chat-header {
  padding: 10px 16px;
  border-bottom: 1px solid #e8e8e8;
  background-color: #fff;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.close-button {
  padding: 4px;
  margin-left: 8px;
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  overflow-x: hidden;
  min-height: 0;
  position: relative;
  max-height: calc(100% - 100px);
}

.message {
  margin-bottom: 12px;
  max-width: 80%;
  clear: both;
}

.message.sent {
  float: right;
}

.message.received {
  float: left;
}

.message-content {
  padding: 8px 12px;
  border-radius: 8px;
  word-break: break-word;
}

.sent .message-content {
  background-color: #1890ff;
  color: white;
}

.received .message-content {
  background-color: #e8e8e8;
  color: #333;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.chat-input {
  display: flex;
  padding: 12px;
  border-top: 1px solid #e8e8e8;
  background-color: #fff;
}

.chat-input .ant-input {
  margin-right: 8px;
}
</style>